package uk.co.javahelp.sender.template;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;

import uk.co.javahelp.sender.message.Message;

public class StringTemplateFormatter implements MessageFormatter {

	public static final String SUBJECT_MARKER = "Subject:";
	
	public static final String LINE_SEPARATOR = "\n"; //System.getProperty("line.separator");
	
	public static final String SLASH = "/";
	
	public static final String RECIPIENT_EMAIL = "recipient_email";
	
	@Override
	public String[] formatMessage(final Message message) throws IOException {
		final String templateText = getTemplateText(message, ".txt");
		if(templateText == null) throw new FileNotFoundException(message.toString());
		final String subjectText = (templateText.startsWith(SUBJECT_MARKER)
		    ? StringUtils.substringBetween(templateText, SUBJECT_MARKER, LINE_SEPARATOR)
		    : StringUtils.substringBefore(templateText, LINE_SEPARATOR)).trim();
		final String bodyText =
		    StringUtils.substringAfter(templateText, LINE_SEPARATOR).trim();
		final String htmlText = getTemplateText(message, ".html");
		
		final StringTemplate subjectTemplate = new StringTemplate(subjectText);
		final StringTemplate bodyTemplate = new StringTemplate(bodyText);
		final StringTemplate htmlTemplate = new StringTemplate(htmlText);
		
		final Map<String, Object> attributes = message.getAttributes();
		attributes.put(RECIPIENT_EMAIL, message.getTo());
	    
		subjectTemplate.setAttributes(attributes);
		bodyTemplate.setAttributes(attributes);
		htmlTemplate.setAttributes(attributes);
		
		return new String[] {
    		subjectTemplate.toString(),
			bodyTemplate.toString(),
			htmlTemplate.toString()
		};
	}
	
	private final String getTemplateText(final Message message, final String suffix)
	        throws IOException {
	    ClassPathResource source = new ClassPathResource(
	    		buildTemplatePath(message.getTemplate(), suffix));
	    if(!source.exists()) {
   	    	return null;
	    }
		final InputStream is = source.getInputStream();
		try {
			final String templateText = IOUtils.toString(is).trim();
			return templateText;
		} finally {
			IOUtils.closeQuietly(is);
		}
	}
	
	private String buildTemplatePath(final String template, final String suffix) {
		final StringBuilder sb = new StringBuilder("/mail/");
		sb.append(template);
		sb.append(suffix);
		return sb.toString();
	}
}
